from httplib import *
from xml.dom import minidom
from re import *
from math import *
import urllib2
import hashlib
import os
import sys
from urllib import urlopen



class engine:
	def __init__(self,cht,runtime,chtDamage,mixDamage,engineNumber):
		self.defaultcht=cht
		self.runtime=runtime
		self.chtDamage=chtDamage
		self.engineNumber=engineNumber
		self.numberOfEngines=XPLMGetDatai(XPLMFindDataRef("sim/aircraft/engine/acf_num_engines"))

	def clearEng(self):
		self.runtime=0
		self.chtDamage=0
		self.mixtureDamage=0

	def engineType(self):
		return 1

	def currentRPM(self):
		return 0

	def currentCHT(self):
		return 200

	def currentMIX(self):
		return 10

	def planeALT(self):
		return 490

	def feed(self,sec,rpm,mix,cht,altitude):
		if rpm>0:
			self.runtime+=sec
		if self.defaultcht>0:
			_diff=abs(cht-self.defaultcht)/float(sec)
			if _diff>0:
				self.chtDamage+=_diff
		self.defaultcht=cht
		if (mix > 95 and altitude > 1000):
			self.mixtureDamage += sec

	def getData(self):
		return "&mixture"+str(self.engineNumber+1)+"="+str(self.mixtureDamage)+"&heat"+str(self.engineNumber+1)+"="+str(self.chtDamage)+"&time"+str(self.engineNumber+1)+"="+str(self.runtime)

	def isEngRun(self):
		return False
		


class PythonInterface:
	def __init__(self):
		self.Name = "X-Economy"
		self.Sig =  "ksgy.Python.XFSEconomy"
		self.Desc = "X-Economy - plugin for FSEconomy (www.fseconomy.com)"
		self.VERSION="1.6b"
		self.MenuItem1 = 0
		self.flying = 0
		self.flightTime = 0
		self.rentalTick = 0
		self.leaseTime = 10
		self.errormessage = 10
		self.CurrentTimeCaption=""
		self.LeaseCaption = 0
		self.Arrived = 0
		self.CurrentAircraft=""
		self.isTacho = 0
		self.FuelTanks=[]
		self.stPayload=0
		self.stEq=0
		self.gsCheat=0
		self.globalX=0
		self.globalY=0
		self.checkfuel=0
		self.err1=""
		self.err2=""
		self.ACEngine=[]
		self.userstr = "abc"
		self.passstr = "1234"
		
		self.checkACState(2, 1, 1, 1)
		self.arrive()

	def XFSEpost(self, query):
		f1 = open(os.path.join('Resources','plugins','PythonScripts','PI_xfse.py'), 'rb')
		filemd5sum = hashlib.md5(f1.read()).hexdigest()
		f1.close()
		print 'http://www.x-plane.hu/x-economy/x-economy.php?md5sum='+filemd5sum+'&'+query
		stuff = urlopen('http://www.x-plane.hu/x-economy/x-economy.php?md5sum='+filemd5sum+'&'+query).read()
		stuff = stuff.replace('&',' and ')
		dom = minidom.parseString(stuff)
		return dom

	def isAllEngineStopped(self):
		_allenginestopped = True
		try:
			for ienga in range(len(self.ACEngine)):
				if self.ACEngine[ienga].isEngRun() > 0:
					_allenginestopped = False
		except Exception:
			_allenginestopped = True

		print "isengstopped"
		return _allenginestopped


	def chkBrk(self,h,b):
		if h == 1:
			return True
		
		if h == 0 and b < float(1.0):
			return True
			
		return False

	def checkACState(self, elapsedMe, elapsedSim, counter, refcon):

		self.errormessage = self.errormessage - 1
		_timecompression=1
		if _timecompression==0:
			_timecompression=1
		_groundcompression=1

		_totalcompression=1/float(_timecompression)
		if self.flying==1:

			
			if _groundcompression>1:
				self.gsCheat+=1

			if self.gsCheat>10:
				self.cancelFlight("You tried to use gound speed compression too much, but it's disabled.","Possibly it's a cheat, your flight was cancelled.")

			isBrake=1
			airspeed=1

			if self.ACEngine[0].engineType() == 3 or self.ACEngine[0].engineType() == 5:
				isHeli = 1
			else:
				isHeli = 0
					  
			if _timecompression > 0: 
			
				#fuel change check
				_fueltotal=20

				if(_fueltotal>self.checkfuel):
					self.cancelFlight("Fuel seem filling while you're flying, flight cancelled.","")

				self.checkfuel=21


				
				# lease time calc
				if self.leaseTime>0: 
					self.leaseTime=int(self.leaseTime)-1
				if self.LeaseCaption:
					_leasehours=self.leaseTime/3600
					_leasemins=(self.leaseTime-_leasehours*3600)/60

					print "Lease time left: "+str(_leasehours)+" hours "+str(_leasemins)+" mins" 
					
					
				if(self.chkBrk(isHeli,isBrake) and self.ACEngine[0].currentRPM()>float(10.0) and airspeed>float(5) and self.ACEngine[0].planeALT()>10):

					self.flightTime=int(self.flightTime)+1
					if self.CurrentTimeCaption:
						_currhours=self.flightTime/3600
						_currmins=(self.flightTime-_currhours*3600)/60
						print "Current flight time: "+str(_currhours)+" hours "+str(_currmins)+" mins"
					# engine feed only when flying: pre-heat recommended on ground
					for iengfeed in range(len(self.ACEngine)):
						#sec,rpm,mix,cht,altitude):
						self.ACEngine[iengfeed].feed(1,self.ACEngine[iengfeed].currentRPM(),self.ACEngine[iengfeed].currentMIX(),self.ACEngine[iengfeed].currentCHT(),self.ACEngine[iengfeed].planeALT())

				# arrive
				else:
					
					if isHeli == 1:
						if(self.flightTime>60 and self.isAllEngineStopped() and self.ACEngine[0].planeALT()<50 and airspeed<float(5)):
							#print "heli arrived"
							self.arrive()
							
					else:
						if(self.flightTime>60 and self.isAllEngineStopped() and self.ACEngine[0].planeALT()<50 and isBrake==1.0 and airspeed<float(30)):
							#print "plane arrived"
							self.arrive()
							


				if self.isTacho==1:
					self.rentalTick+=(self.ACEngine[0].currentRPM()/float(3600.0))

			if(self.stEq=="0"):
				self.disableAP()
				self.disableGPS()
				self.disableIFR()

			if(self.stEq=="1"):
				self.disableAP()
				self.disableGPS()

			if(self.stEq=="2"):
				self.disableAP()
				self.disableIFR()

			if(self.stEq=="4"):
				self.disableGPS()
				self.disableIFR()

			if(self.stEq=="3"):
				self.disableAP()

			if(self.stEq=="5"):
				self.disableGPS()

			if(self.stEq=="6"):
				self.disableIFR()

			XPLMSetDataf(XPLMFindDataRef("sim/flightmodel/weight/m_fixed"),float(self.stPayload))

		return float(_totalcompression)

	def disableGPS(self):
		print "dis GPS"

	def disableAP(self):
		print "dis ap"
		
	def disableIFR(self):
		print "dis ifr"


	def enableAllInstruments(self):
		print "dis all"


	def arrive(self):
		print "arrive"
		self.Arrived = 0
		if self.Arrived==0:
			print "arrive1"
			self.Arrived=1
			self.leaseTime = 20
			if self.leaseTime>0:
				
				print "arrived"
				
				_PlaneLatdr = 13.554
				_PlaneLondr = 47.552
				_lat = 13.555
				_lon = 47.552

				_totalfuel = 0

				_fueltanksQTY = []
				_fueltanksQTY.append(10)
				_fueltanksQTY.append(10)
				_fueltanksQTY.append(10)
				_fueltanksQTY.append(10)
				_fueltanksQTY.append(10)
				
				
				for _iTotFuel in range(5):
					_totalfuel = _totalfuel + _fueltanksQTY[_iTotFuel]/float(2.68735)
					
				print _totalfuel

				#print "arrived1"
				
				_iFuel=0
				
				_actfueltanks=5
						
				print _actfueltanks
				
				_iFuel=0
				_fuelarray=[]
				_eachfuel=_totalfuel/float(_actfueltanks) # thx no2 jck :)
				
				self.FuelTanks.append(10)
				self.FuelTanks.append(0)
				self.FuelTanks.append(10)
				self.FuelTanks.append(10)
				self.FuelTanks.append(10)
				self.FuelTanks.append(10)
				self.FuelTanks.append(10)
				self.FuelTanks.append(10)
				self.FuelTanks.append(10)
				self.FuelTanks.append(10)
				self.FuelTanks.append(10)
				self.FuelTanks.append(10)
				
				for _iFuel in range(len(self.FuelTanks)):
					if self.FuelTanks[_iFuel]==0:
						_fuelarray.append(0)
					else:
						_fuelarray.append(_eachfuel)


				#print "arrived2"
				
				_c=_fuelarray[0]
				_lm=_fuelarray[1]
				_la=_fuelarray[2]
				_let=_fuelarray[3]
				_rm=_fuelarray[4]
				_ra=_fuelarray[5]
				_rt=_fuelarray[6]
				_c2=_fuelarray[7]
				_c3=_fuelarray[8]
				_x1=_fuelarray[9]
				_x2=_fuelarray[10]

				_engineStr=""
				for _ieng in range(len(self.ACEngine)):
					_engineStr=_engineStr+str(self.ACEngine[_ieng].getData())
					
				#print "arrived3"

				if self.isTacho==1:
					_finishflight=self.XFSEpost("user="+self.userstr+"&pass="+self.passstr+"&action=arrive&rentalTick="+str(int(self.rentalTick))+"&lat="+str(_lat)+"&lon="+str(_lon)+"&c="+str(_c)+"&lm="+str(_lm)+"&la="+str(_la)+"&let="+str(_let)+"&rm="+str(_rm)+"&ra="+str(_ra)+"&rt="+str(_rt)+"&c2="+str(_c2)+"&c3="+str(_c3)+"&x1="+str(_x1)+"&x2="+str(_x2)+_engineStr)
				else:
					_finishflight=self.XFSEpost("user="+self.userstr+"&pass="+self.passstr+"&action=arrive&rentalTime="+str(self.flightTime)+"&lat="+str(_lat)+"&lon="+str(_lon)+"&c="+str(_c)+"&lm="+str(_lm)+"&la="+str(_la)+"&let="+str(_let)+"&rm="+str(_rm)+"&ra="+str(_ra)+"&rt="+str(_rt)+"&c2="+str(_c2)+"&c3="+str(_c3)+"&x1="+str(_x1)+"&x2="+str(_x2)+_engineStr)

				#print "arrived4"
				
				if len(_finishflight.getElementsByTagName('result'))>0:
					_err=_finishflight.getElementsByTagName('result')[0].firstChild.data
					_errA=_err.split('|')
					
					for ierr in range(len(_errA)):
						if _errA[ierr]>80:
							_terrA=_errA[ierr].split('.')
							XPSetWidgetDescriptor(self.ErrorCaption[ierr], _terrA[0])
							XPSetWidgetDescriptor(self.ErrorCaption[ierr+1], _terrA[1].lstrip())
						else:
							XPSetWidgetDescriptor(self.ErrorCaption[ierr], _errA[ierr])

					XPSetWidgetProperty(self.StartFlyButton, xpProperty_Enabled, 1)
					XPSetWidgetProperty(self.CancelFlyButton, xpProperty_Enabled, 0)
					
				#print "arrived5"

			else:
				self.cancelFlight("Lease time is over. Your flight was cancelled, sorry, you have to re-fly this trip.","")
				
			#print "arrived6"
			
			self.flightTime=0
			self.enableAllInstruments()
			
			#print "arrived7"


	def cancelFlight(self,message,message2):
		self.flying=0

		cancelflight=self.XFSEpost("user="+self.userstr+"&pass="+self.passstr+"&action=cancel")
		if (cancelflight.getElementsByTagName('response')[0].firstChild.nodeName=="ok"):
			
			self.err1 = message
			self.err2 = message2
			self.errormessage = 10
			
			print message
			print message2
			
		#print "cancel flight1: " + message
		#print "cancel flight2: " + message2


	def addAssignment(self,aIndex,aFrom,aTo,aCargo):
		print "add assignment"

	def CreateXFSEWidget(self, x, y, w, h):
		#read ini file
		try:
			_INIfile=open(os.path.join('Resources','plugins','PythonScripts','x-economy.ini'), 'r')
			_userINI=_INIfile.readline()
			_userINI=_userINI.replace('\n','')
			_passINI=_INIfile.readline()
			_INIfile.close()
			#print "ini successfully readed"

		except IOError, (errno, strerror):
			_userINI=""
			_passINI=""
			#print "no ini file, creating an empty one"


		

	def XFSEHandler(self, inMessage, inWidget,    inParam1, inParam2):


		if (inMessage == "pushbutton"):
			#print "button pressed"
			if (inParam1 == "LoginButton"):
				#print "login"
				self.userstr="stonyo"
				self.passstr="V9RA4MBS"
				logincheck=self.XFSEpost("user="+self.userstr+"&pass="+self.passstr+"&action=accountCheck")
				print "logincheck"


				if (logincheck.getElementsByTagName('response')[0].firstChild.nodeName=="ok"):
					print "Logged in!"
					#print "login successful"
					
				else:
					#print "login was not successful"
					
					if(logincheck.getElementsByTagName('response')[0].firstChild.nodeName=="notok"):
						print "New version available, see below..."
						#print "new version avail"

					else:
						print "Invalid account!"
						#print "invalid account"

				logincheck.unlink()
				return 1

			if (inParam1 == "StartFlyButton"):
				#print "start flying"
				_INIFileW=open(os.path.join('Resources','plugins','PythonScripts','x-economy.ini'), 'w')
				_INIFileW.write(self.userstr+'\n'+self.passstr)
				_INIFileW.close()
				self.CurrentAircraft="valamilyen aircraft"

				#clear prev a/c's engines
				self.ACEngine = []

				# set up engines
				self.NumberOfEngines=3
				_OAT=21

				for _iengApp in range(self.NumberOfEngines):
					self.ACEngine.append(engine(_OAT,0,0,0,_iengApp))


				self.FromCaption=[]
				self.ToCaption=[]
				self.CargoCaption=[]

				#print _stmp2

				if self.CurrentAircraft=="":
					print  "Unknown aircraft: If you're sure this is an FSE compatible aircraft, please edit"
				else:
					PlaneLatdr = 46.555
					PlaneLondr = 19.444
					Lat = 46.555
					Lon = 19.444
					self.err1=""
					self.err2=""

					startFlight=self.XFSEpost("user="+self.userstr+"&pass="+self.passstr+"&action=startFlight&lat="+str(Lat)+"&lon="+str(Lon)+"&aircraft="+self.CurrentAircraft)
					if startFlight.getElementsByTagName('response')[0].firstChild.nodeName=="error":
						#print startFlight.getElementsByTagName('error')[0].firstChild.data
						print startFlight.getElementsByTagName('error')[0].firstChild.data
					else:

						
						stFrom="-"
						stTo="-"
						stCargo="-"

						for iAssignment in range(len(startFlight.getElementsByTagName('assignment'))):
							self.addAssignment(iAssignment,str(startFlight.getElementsByTagName('from')[iAssignment].firstChild.data),str(startFlight.getElementsByTagName('to')[iAssignment].firstChild.data),str(startFlight.getElementsByTagName('cargo')[iAssignment].firstChild.data))

						Accounting=startFlight.getElementsByTagName('accounting')[0].firstChild.data
						if Accounting=="tacho":
							self.isTacho=1

						self.stEq=startFlight.getElementsByTagName('equipment')[0].firstChild.data

						if(self.stEq=="0"):
							stEquipment=" (VFR)"
						if(self.stEq=="1"):
							stEquipment=" (IFR)"
						if(self.stEq=="2"):
							stEquipment=" (GPS)"
						if(self.stEq=="4"):
							stEquipment=" (AP)"
						if(self.stEq=="3"):
							stEquipment=" (IFR, GPS)"
						if(self.stEq=="5"):
							stEquipment=" (AP, IFR)"
						if(self.stEq=="6"):
							stEquipment=" (AP, GPS)"
						if(self.stEq=="7"):
							stEquipment=" (IFR, AP, GPS)"

						stACReg=startFlight.getElementsByTagName('registration')[0].firstChild.data
						stLE=startFlight.getElementsByTagName('leaseExpires')[0].firstChild.data
						print "Aircraft registration: "+str(stACReg)+str(stEquipment)
						self.leaseTime = 0
						self.leaseTime=int(stLE)
						print "Lease time: "+str(int(stLE)/3600)+" hours"

						# set weight and fuel
						self.stPayload=startFlight.getElementsByTagName('payloadWeight')[0].firstChild.data
						stFuel=startFlight.getElementsByTagName('fuel')[0].firstChild.data
						print self.stPayload
						astFuel=stFuel.split(' ')
						self.FuelTanks=[]

						totalFuel=float(0)
						for iFuel in range(len(astFuel)-1):
							totalFuel+=float(astFuel[iFuel])

							if float(astFuel[iFuel])>float(0):
								self.FuelTanks.append(1)
							else:
								self.FuelTanks.append(0)

						num_tanks = 5 # thx sandy barbour :)
						currentFuel = totalFuel*float(2.68735)
						_it=0
						_fuelPerTanks = []
						for _it in range(num_tanks):
							_currentRatio[_it] = [_it/10]
							#XPLMGetDatavf(XPLMFindDataRef("sim/aircraft/overflow/acf_tank_rat"),_currentRatio,0,num_tanks)
							_fuelPerTanks.append(currentFuel*_currentRatio[_it])								

						self.checkfuel=20


						self.Arrived=0
						self.flightTime = 0
						self.flying=1 # start flight query
						self.rentalTick = 0
						self.gsCheat = 0

						for iengclear in range(len(self.ACEngine)):
							self.ACEngine[iengclear].clearEng()

					startFlight.unlink()
					return 1

			if (inParam1 == "CancelFlyButton"):
				self.cancelFlight("Flight cancelled.","")
				#print "flight cancelled by user"

			if (inParam1 == self.UpdateButton):
				#print "update client - by user"
				_newClient = urlopen('http://x-plane.indexf1.hu/xfse/PI_xfse.py').read()
				_oldClient=open(os.path.join('Resources','plugins','PythonScripts','PI_xfse.py'), 'w')
				_oldClient.write(_newClient)
				_oldClient.close()
				self.err1 = "Your client is updated, please restart X-Plane,"
				self.err2 = "or reload plugins via Plugins / Python Interface / Control Panel"

		return 0
		
		
		
PythonInterface()